package dyu.Questionnaire;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.PendingIntent;
import android.telephony.SmsManager;
import android.view.ViewGroup.LayoutParams;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends Activity {	
	public static int INPUT_PHONE_NUMBER = 0;
	Button[] btnList;
    SharedPreferences prefs;
    //String prefName = getResources().getString(R.string.prefName);
    public static final String prefName = "PopupPref";
	int[] lastAnswerWeek;
    int[] currentAnswerStatus; 
    Date dateStarted;
    int numberOfGroups;
    int onPauseForAnswer=0;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //Toast.makeText(this, "On Create...", Toast.LENGTH_SHORT).show();
        
        setContentView(R.layout.main);
        LinearLayout layout = (LinearLayout) findViewById(R.id.mainLayout);
        layout.setOrientation(LinearLayout.VERTICAL);
        LayoutParams params= new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        
        this.prefs = getSharedPreferences(this.prefName, MODE_PRIVATE);
        boolean firstRun = this.prefs.getBoolean("firstRun", true);
        if(firstRun == true)
        {
        	
        	Intent i = new Intent("dyu.Questionnaire.InputPhoneNumber");
        	startActivityForResult(i, INPUT_PHONE_NUMBER);
        }
        else
        {
        
        this.GetNumberOfGroup();
        this.LoadOldData();
        this.GetCurrentAnswerStatus();
        
        for(int groupNumber=1; groupNumber<=this.numberOfGroups; groupNumber++){
        	int ques = this.getResources().getIdentifier("Group" + groupNumber + "_Question", "array", this.getPackageName());
        	String[] questionsList = getResources().getStringArray(ques);
        	Button btn = new  Button(this);
            //you can change this line to  btn.setText(""+questionsList[0]);
            btn.setText("問卷 "  + groupNumber + ": "  + questionsList[0]);
            if(this.currentAnswerStatus[groupNumber-1]!=1) btn.setEnabled(false);
            this.btnList[groupNumber - 1] = btn;	
        	btn.setLayoutParams(params);    
        	final int q=groupNumber;
        	btn.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					// TODO Auto-generated method stub					
					onPauseForAnswer=1;
					Intent i = new Intent("dyu.Questionnaire.Group1");
					Bundle extras = new Bundle();
					extras.putString("questionNumber", Integer.toString(q));
					i.putExtras(extras);
					startActivityForResult(i,1);
				}
			});
            layout.addView(btn);
        }
    }
    }
    @Override 
    protected void onPause() {        
        this.SaveCurrentData();
        super.onPause();
        if(this.onPauseForAnswer!=1){
        	finish();
        	Intent intentOfService = new Intent(getBaseContext(), MyService.class);
			Bundle extras = new Bundle();
			extras.putString("timeCalled", "time started");
			intentOfService.putExtras(extras);
        	this.startService(intentOfService);
        } 	
    }
    public void onActivityResult(int requestCode, int resultCode, Intent data){
    	
    	this.onPauseForAnswer=0;
    	if(resultCode==RESULT_OK){
    		
    		Bundle extras = data.getExtras();
    		if(extras != null){
    			String answerResult = extras.getString("AnswerResult");
        		String groupNumber = extras.getString("G_Number");
    			int groupN = Integer.parseInt(groupNumber);
    			this.btnList[groupN - 1].setEnabled(false);
    			this.lastAnswerWeek[groupN-1] = this.GetCurrentWeek();
    			if(this.dateStarted == null) this.dateStarted = Calendar.getInstance().getTime();
    			sendSMS(answerResult);
    		}
    		
    		if(requestCode == INPUT_PHONE_NUMBER){
    			if (resultCode == RESULT_OK) {
    		
    			    this.prefs = getSharedPreferences(this.prefName, MODE_PRIVATE);
    		    	SharedPreferences.Editor editor = this.prefs.edit();
    		        editor.putBoolean("firstRun", false);
    			    Toast.makeText(getBaseContext(), "Input Phone Number", Toast.LENGTH_LONG).show();
    		        editor.commit();
    			}
    		}
    	}
    }
    
    private void sendSMS(String smsResult)
    {        
        PendingIntent pi = PendingIntent.getActivity(this, 0,
            new Intent(this,Object.class), 0);                
        SmsManager sms = SmsManager.getDefault();
        String phoneNumber = prefs.getString("phoneNumber", "0");    
        sms.sendTextMessage(phoneNumber, null, smsResult, pi, null); 
        Toast.makeText(getBaseContext(), "訊息已傳送", Toast.LENGTH_LONG).show();
    } 
      
    private int GetCurrentWeek(){
    	int currentWeek = 0;
    	if(this.dateStarted == null) currentWeek = 1;
    	else{    		
    		Calendar calendar1 = Calendar.getInstance();
    		Calendar calendar2 = Calendar.getInstance();
    		
    		calendar1.setTime(Calendar.getInstance().getTime());//current date
    		calendar2.setTime(this.dateStarted);// beginning date
    		
    		//calculate the different days from these two days
    		long diffDays = (calendar1.getTimeInMillis() - calendar2.getTimeInMillis()) / (24 * 60 * 60 * 1000) + 1;
    		
    		if((diffDays) % 7 == 0 && diffDays != 0) currentWeek = (int) diffDays / 7;
    		else currentWeek = (int) diffDays/7 + 1;
    	}
    	
    	return currentWeek;
    }
    
    private void GetCurrentAnswerStatus(){
    	
    	int currentWeek = this.GetCurrentWeek();
    	
    	this.currentAnswerStatus = new int[this.numberOfGroups];
    	
    	for(int group=1; group<= this.numberOfGroups; group++){
    		
    		this.currentAnswerStatus[group-1] = 0;
    		
    		//check if this week requests the answer.
    		int popupID = this.getResources().getIdentifier("popupSchedule_Group" + group, "array", this.getPackageName());
    		
    		String[] weekList = getResources().getStringArray(popupID);
    		
			for(int i=0; i<weekList.length; i++){
				int temp = Integer.parseInt(weekList[i]);
				if(temp == currentWeek){
					this.currentAnswerStatus[group-1] = 1;
					break;
				}
				else if(temp > currentWeek) 
					break;
			}
			
			//check if this group of question be answered in this week?
			if(this.currentAnswerStatus[group-1] == 1){
				int lastAnswerWeekOfGroup = this.lastAnswerWeek[group-1];
				if(lastAnswerWeekOfGroup == currentWeek) 
					this.currentAnswerStatus[group-1] = 2;
			}
			
    	}
    }
   
    private void GetNumberOfGroup(){
    	int groupNumber = 1;
    	while(true){
        	
        	int ques = this.getResources().getIdentifier("Group" + groupNumber + "_Question", "array", this.getPackageName());
        	
        	if(ques==0) break;
        	
        	groupNumber++;
    	}
    	this.numberOfGroups = groupNumber - 1;
    }
    
    private void LoadOldData(){
    	this.btnList = new Button[this.numberOfGroups];
    	this.lastAnswerWeek = new int[this.numberOfGroups];
    	
    	//------load all old variables data------------------
    	this.prefs = getSharedPreferences(this.prefName, MODE_PRIVATE);
    	//if(this.prefs == null) return;
    	
    	int day = this.prefs.getInt("day", 0);
    	int month = this.prefs.getInt("month", 0);
    	int year = this.prefs.getInt("year", 0);
    	
    	for(int i=0; i<this.numberOfGroups; i++){
    		this.lastAnswerWeek[i] = this.prefs.getInt("LastWeekAnswer"+i, 0);
    	}
    	
    	if(day ==0) {
    		this.dateStarted = null;
    		return;    	
    	}
    	this.dateStarted = new Date(year, month, day);
    	    	
    }
    
    private void SaveCurrentData(){
    	this.prefs = getSharedPreferences(this.prefName, MODE_PRIVATE);
    	SharedPreferences.Editor editor = this.prefs.edit();
    	
    	if(this.dateStarted == null) return;
    	
    	//----save all task in task list to share preference----
    	
    	//------save dateStated variable-------------------
    	editor.putInt("day", this.dateStarted.getDate());
    	editor.putInt("month", this.dateStarted.getMonth());
    	editor.putInt("year", this.dateStarted.getYear());
    	
    	//------save lastAnswerWeek variable-------------------
    	for(int i=0; i<this.numberOfGroups; i++){
    		editor.putInt("LastWeekAnswer"+i, this.lastAnswerWeek[i]);
    	}
    	
    	editor.commit();
    }
     
     @Override
     public void onBackPressed() {

        return;
     }
   //--- Create Option Menu ---//
   		public boolean onCreateOptionsMenu(Menu menu){
   			super.onCreateOptionsMenu(menu);
   			menu.add(0, 0, 0, "Settings").setIcon(R.drawable.ic_menu_setting);
   			
   			return true;
   		}
   		public boolean onOptionsItemSelected(MenuItem item){
   			switch(item.getItemId()){
   			
   			case 0:
   				
   				Intent i = new Intent(getBaseContext(), InputPhoneNumber.class);
				startActivity(i);
				
				finish();
				return true;
   			}
   			return false;
				
}
   		}